package com.tianji.learning.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tianji.api.client.user.UserClient;
import com.tianji.api.dto.user.UserDTO;
import com.tianji.common.domain.dto.PageDTO;
import com.tianji.common.exceptions.BadRequestException;
import com.tianji.common.exceptions.BizIllegalException;
import com.tianji.common.utils.BeanUtils;
import com.tianji.common.utils.CollUtils;
import com.tianji.common.utils.UserContext;
import com.tianji.learning.domain.dto.ReplyDTO;
import com.tianji.learning.domain.po.InteractionQuestion;
import com.tianji.learning.domain.po.InteractionReply;
import com.tianji.learning.domain.query.ReplyPageQuery;
import com.tianji.learning.domain.vo.ReplyVO;
import com.tianji.learning.enums.QuestionStatus;
import com.tianji.learning.mapper.InteractionQuestionMapper;
import com.tianji.learning.mapper.InteractionReplyMapper;
import com.tianji.learning.service.IInteractionReplyService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.function.Predicate;
import java.util.stream.Collectors;

/**
 * <p>
 * 互动问题的回答或评论 服务实现类
 * </p>
 *
 * @author 林云
 * @since 2023-08-13
 */
@Service
@RequiredArgsConstructor
public class InteractionReplyServiceImpl extends ServiceImpl<InteractionReplyMapper, InteractionReply> implements IInteractionReplyService {

    private final InteractionQuestionMapper questionMapper;

    private final UserClient userClient;

    /**
     * 新增回答或评论
     */
    @Override
    public void saveReply(ReplyDTO replyDTO) {
        //1.获取登录用户id
        Long userId = UserContext.getUser();
        //2.保存到回答或评论表 interaction_reply
        InteractionReply reply = BeanUtils.copyBean(replyDTO, InteractionReply.class);
        reply.setUserId(userId);//补充属性
        this.save(reply);
        //获取问题实体
        InteractionQuestion question = questionMapper.selectById(replyDTO.getQuestionId());
        //3.判断是回答还是评论 即判断answerId是否存在
        if (replyDTO.getAnswerId() != null) {
            //3.1如果是评论 新增评论数量
            InteractionReply answerInfo = this.getById(replyDTO.getAnswerId());
            reply.setReplyTimes(answerInfo.getReplyTimes() + 1);
            this.updateById(answerInfo);
        } else {
            //3.2如果是回答 新增回答数量 修改最近回答id
            question.setAnswerTimes(question.getAnswerTimes() + 1);
            question.setLatestAnswerId(reply.getId());//刚才雪花算法已经生成id
        }
        //4.如果是学生提交的 则改status为未查看
        if (replyDTO.getIsStudent()) {
            question.setStatus(QuestionStatus.UN_CHECK);
        }
        questionMapper.updateById(question);
    }

    /**
     * 分页查询回答或评论列表
     */
    @Override
    public PageDTO<ReplyVO> queryReplyPage(ReplyPageQuery query) {
        //1.参数校验
        Long answerId = query.getAnswerId();
        Long questionId = query.getQuestionId();
        if (answerId == null && questionId == null) {
            throw new BadRequestException("问题id和回答id不能都为空");
        }
        //2.查询回答表 answerId questionId
        Page<InteractionReply> page = this.lambdaQuery()
                .eq(InteractionReply::getAnswerId, answerId == null ? 0L : answerId)
                .eq(questionId != null, InteractionReply::getQuestionId, questionId)
                .page(query.toMpPageDefaultSortByCreateTimeDesc());
        List<InteractionReply> records = page.getRecords();
        if (CollUtils.isEmpty(records)) {
            return PageDTO.empty(page);
        }
        Set<Long> userIds = new HashSet<>();
        Set<Long> targetReplyIds = new HashSet<>();
        for (InteractionReply record : records) {
            //匿名不加
            if (!record.getAnonymity()) {
                userIds.add(record.getUserId());
                userIds.add(record.getTargetUserId());
            }
            if (record.getTargetReplyId() != null && record.getTargetReplyId() > 0) {
                targetReplyIds.add(record.getTargetReplyId());
            }
        }
        //3.收集目标用户id列表
        if (targetReplyIds.size() > 0) {
            List<InteractionReply> replyList = this.listByIds(targetReplyIds);
            //要过滤掉匿名用户
            Set<Long> targetUserIds = replyList.stream()
                    .filter(Predicate.not(InteractionReply::getAnonymity))
                    .map(InteractionReply::getUserId)
                    .collect(Collectors.toSet());
            //统一给userIds
            userIds.addAll(targetUserIds);
        }
        //远程调用查询
        List<UserDTO> userDTOS = userClient.queryUserByIds(userIds);
        if (CollUtils.isEmpty(userDTOS)) {
            throw new BizIllegalException("用户不存在");
        }
        Map<Long, UserDTO> userMap = userDTOS.stream().collect(Collectors.toMap(UserDTO::getId, c -> c));
        //封装vo
        List<ReplyVO> list = new ArrayList<>();
        for (InteractionReply reply : records) {
            ReplyVO replyVO = BeanUtils.copyBean(reply, ReplyVO.class);
            if (!reply.getAnonymity()) {
                UserDTO user = userMap.get(reply.getUserId());
                if (user != null) {
                    replyVO.setUserName(user.getName());
                    replyVO.setUserIcon(user.getIcon());
                    replyVO.setUserType(user.getType());
                }
            }
            UserDTO targetUser = userMap.get(reply.getTargetUserId());
            if (targetUser != null) {
                replyVO.setTargetUserName(targetUser.getName());
            }
            list.add(replyVO);
        }
        return PageDTO.of(page, list);
    }
}
